/*
 * Copyright 1999-2011 Alibaba Group.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.dubbo.container.log4j2;

import java.nio.charset.Charset;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.appender.rolling.CronTriggeringPolicy;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;

import com.alibaba.dubbo.common.utils.ConfigUtils;
import com.alibaba.dubbo.container.Container;

/**
 * Log4j2Container. (SPI, Singleton, ThreadSafe)
 * 
 * @author chenrong
 */
public class Log4j2Container implements Container {

    public static final String LOG4J2_SUBDIRECTORY = "dubbo.log4j.subdirectory";

    public static final String LOG4J2_FILE = "dubbo.log4j.file";

    public static final String LOG4J2_LEVEL = "dubbo.log4j.level";

    public static final String DEFAULT_LOG4J2_LEVEL = "ERROR";

    @Override
    public void start() {
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();
        String file = ConfigUtils.getProperty(LOG4J2_FILE);
        if (file != null && file.length() > 0) {
            String level = ConfigUtils.getProperty(LOG4J2_LEVEL);
            if (level == null || level.length() == 0) {
                level = DEFAULT_LOG4J2_LEVEL;
            }
            Level lvl = Level.ERROR;
            if (level.equals("ALL")) {
                lvl = Level.ALL;
            } else if (level.equals("TRACE")) {
                lvl = Level.TRACE;
            } else if (level.equals("DEBUG")) {
                lvl = Level.DEBUG;
            } else if (level.equals("INFO")) {
                lvl = Level.INFO;
            } else if (level.equals("WARN")) {
                lvl = Level.WARN;
            } else if (level.equals("ERROR")) {
                lvl = Level.ERROR;
            } else if (level.equals("FATAL")) {
                lvl = Level.FATAL;
            } else if (level.equals("OFF")) {
                lvl = Level.OFF;
            }

            PatternLayout layout = PatternLayout.createLayout("%d [%t] %-5p %C{6} (%F:%L) - %m%n", null, config, null,
                    Charset.forName("UTF-8"), true, false, null, null);
            final String subdirectory = ConfigUtils.getProperty(LOG4J2_SUBDIRECTORY);
            if (subdirectory != null && subdirectory.length() > 0) {
                int i = file.replace('\\', '/').lastIndexOf('/');
                String path;
                if (i == -1) {
                    path = subdirectory;
                } else {
                    path = file.substring(0, i);
                    if (!path.endsWith(subdirectory)) {
                        path = path + "/" + subdirectory;
                    }
                    file = file.substring(i + 1);
                }
                file = path + "/" + file;
            }

            Appender appender = RollingFileAppender.createAppender(file, "'.'%d{yyyy-MM-dd}-%i", "true", "File",
                    "false", "8192", "true", CronTriggeringPolicy.createPolicy(config, "true", "0 0 0 * * ?"), null,
                    layout, null, "false", "false", null, config);
            appender.start();
            config.addAppender(appender);
            AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
            AppenderRef[] refs = new AppenderRef[] { ref };
            LoggerConfig loggerConfig = LoggerConfig.createLogger("false", lvl, "org.apache.logging.log4j", "true",
                    refs, null, config, null);
            loggerConfig.addAppender(appender, null, null);
            config.addLogger("org.apache.logging.log4j", loggerConfig);
            ctx.updateLoggers();
        }
    }

    @Override
    public void stop() {
    }

}
